/**
 * 依赖：jQuery
 * 用法：
 * new share_app({
 *       ele: 'shareBtn',//分享按钮的ID，默认为“shareBtn”
 *       config: {//分享需要的参数
 *           title : '<{$invitation.title}>',
 *           description : '<{$invitation.description}>',
 *           thumbnail_pic : '<{$invitation.thumbnail_pic}>',
 *           invite_url : '<{$invitation.invite_url}>',
 *       },
 * 	     success: function(){//分享成功之后的回调（限于微信）
 * 			
 *       },
 *       beforeShare: function(next){//在分享之前的钩子
 *          //书写你自己的逻辑
 *
 *          next();//最后一定要调用这个方法
 *       }
 *  })
 */
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD (Register as an anonymous module)
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS
        module.exports = factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {
    var share_app = function(params){
        this.ele = params.ele || 'shareBtn';
        if(!params.config){
            console.error('请添加config属性');
            return;
        }
        if(!params.config.title){
            console.error('请给config添加数据');
            return;
        }
        this.config = params.config;
        this.success = params.success;
        this.beforeShare = params.beforeShare;
        this.init();
    };

    var isweixin = function(){
        var ua = navigator.userAgent.toLowerCase();
        if(ua.match(/MicroMessenger/i)=="micromessenger") {
            return true;
        } else {
            return false;
        }
    };
    //获取微信环境下微信的config
    var getwxconfig = function(callback){
        $.ajax({
            url: '/wap/subject-weixin_action.html',
            type: 'GET',
            data:{'keyUrl':window.location.href},
            success: function(result){
                if(result){
                    result = JSON.parse(result);
                    if(result.error){
                        console.log(result.error);
                        return;
                    }else{
                        callback && callback(result.success);
                    }
                }
            },
            error: function(){
                console.log('error')
            }
        });
    };
    share_app.prototype.init = function(){
        var self = this;
        //获取分享按钮的ID
        var _shareBtn = document.getElementById(self.ele);
        //创建文档碎片
        var fragment = document.createDocumentFragment();
        //在微信环境下
        if(isweixin()){
            //创建并添加微信要用的元素
            var _shareBg = document.createElement('div');
            var _shareImg = document.createElement('div');
            _shareBg.className = 'shareBg';
            _shareBg.style.cssText = 'display: none;background:rgba(0,0,0,0.3);position:fixed;top: 0;left: 0;bottom: 0;right: 0;z-index:19910217;';
            _shareImg.className = 'shareImg';
            _shareImg.style.cssText = "display:none;width:125px;height:104px;background:url('https://pic.solux.cn/Mobile/wap-2017/share.png') no-repeat;background-size:contain;position:fixed;z-index:19910217;top:10px;right:20px;";
            fragment.appendChild(_shareBg);
            fragment.appendChild(_shareImg);

            var _getWxStart = function(parm){
                wx = typeof define === 'function' && define.amd ? parm : wx;
                //获取微信config的信息
                getwxconfig(function(result){
                    wx.config({
                        debug: false,
                        appId: result.appId,
                        timestamp: result.timestamp,
                        nonceStr: result.nonceStr,
                        signature: result.signature,
                        jsApiList: ['onMenuShareAppMessage','hideMenuItems','onMenuShareTimeline']//'hideMenuItems'
                    });
                    wx.ready(function(){
                        //分享给朋友
                        wx.onMenuShareAppMessage({
                            title: self.config.title, // 分享标题
                            desc: self.config.description, // 分享描述
                            link: self.config.invite_url+'?f=wx', // 分享链接
                            imgUrl: self.config.thumbnail_pic, // 分享图标
                            type: '', // 分享类型,music、video或link，不填默认为link
                            dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                            success: function () {
                                // 用户确认分享后执行的回调函数
                                closeShare();
                            },
                            cancel: function () {
                                // 用户取消分享后执行的回调函数
                                closeShare();
                            }
                        });
                        //分享朋友圈
                        wx.onMenuShareTimeline({
                            title: self.config.title, // 分享标题
                            link: self.config.invite_url+'?f=wx', // 分享链接
                            imgUrl: self.config.thumbnail_pic, // 分享图标
                            success: function () {
                                // 用户确认分享后执行的回调函数
                                closeShare();
                            },
                            cancel: function () {
                                // 用户取消分享后执行的回调函数
                                closeShare();
                            }
                        });
                        //wx.hideOptionMenu();
                        //隐藏部分菜单
                        wx.hideMenuItems({
                            menuList: ['menuItem:openWithQQBrowser','menuItem:share:qq','menuItem:openWithSafari','menuItem:share:email','menuItem:readMode','menuItem:copyUrl','menuItem:share:QZone']
                        });
                    });
                });
            }

            if (typeof define === 'function' && define.amd) {
                require(['jsWeixin'], function(wx) {
                    _getWxStart(wx);
                    document.body.appendChild(fragment);
                });
            }else{
                var _jweixin = document.createElement('script');
                _jweixin.setAttribute('src','https://res.wx.qq.com/open/js/jweixin-1.2.0.js');
                fragment.appendChild(_jweixin);
                document.body.appendChild(fragment);

                //在jweixin加载完成后进行赋值操作
                _jweixin.onload = function(){
                    _getWxStart();
                };
            }

            //点击分享按钮和背景图片
            function showShare(){
                _shareImg.style.display = 'block';
                _shareBg.style.display = 'block';
            }
            function closeShare(){
                _shareImg.style.display = 'none';
                _shareBg.style.display = 'none';
            }
            _shareBtn.addEventListener('click', function(event){
                event.stopPropagation();
                //如果有前置操作
                if(typeof self.beforeShare == 'function'){
                    self.beforeShare(showShare);
                }
                else{
                    showShare();
                }
            });

            _shareBg.addEventListener('click', function(event){
                event.stopPropagation();
                closeShare();
            })

        }else{//非微信环境下

            var _getAppStart = function(parm){
                
                if(typeof define === 'function' && define.amd){
                    soshm = parm;
                }

                var userAgent = navigator.userAgent;
                var isQQ = /AppleWebKit.+(MQQBrowser).+Mobile/.test(userAgent);
                var isUC = /AppleWebKit.+(UCBrowser).+Mobile/.test(userAgent);

                var next = function(){
                    if(isQQ || isUC){
                        soshm.popIn({
                            title: self.config.title,
                            url:self.config.invite_url,
                            digest:self.config.description,
                            pic:self.config.thumbnail_pic,
                            sites: ['weixin', 'weixintimeline', 'weibo', 'qzone','qq']
                        });
                    }else{
                        soshm.popIn({
                            title: self.config.title,
                            url:self.config.invite_url,
                            digest:self.config.description,
                            pic:self.config.thumbnail_pic,
                            sites: ['weibo', 'qzone','qq']
                        });
                    }
                }

                if(_shareBtn){
                    _shareBtn.addEventListener('click', function(event){
                        event.stopPropagation();
                        if(self.beforeShare && !self.beforeShare(next)){
                            self.beforeShare(next);
                        }else{
                            next();
                        }
                    });
                }else{
                    console.warn('如果想用share_app,请在页面上添加id为shareBtn');
                }
            }

            if (typeof define === 'function' && define.amd) {
                require(['soshm'], function(soshm) {
                    _getAppStart(soshm);
                });
            }else{
                var _share = document.createElement('script');
                _share.setAttribute('src','/wap_themes/solux/assets/js/vip/soshm.js');
                fragment.appendChild(_share);
                document.body.appendChild(fragment);

                _getAppStart();
            }
            
        }
    };

    window.share_app = share_app;
}));